package cn.hxzy.teacher.controller;


import cn.hxzy.common.domain.User;
import cn.hxzy.common.domain.UserInfo;
import cn.hxzy.common.domain.vo.AddUserVo;
import cn.hxzy.common.listenr.StudentListener1;
import cn.hxzy.common.response.R;
import cn.hxzy.common.response.StatusEnum;
import cn.hxzy.teacher.service.TeacherService;
import cn.hxzy.common.util.ThreadLocalUtil;
import cn.hxzy.user.service.UserService;
import com.alibaba.excel.EasyExcel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.List;

/**
 * @Author wangboyu
 * @Description TODO
 * @Date 2024/7/6 15:54
 */
@RestController
@CrossOrigin
@RequestMapping("/excel")
public class ExcelController {

    @Autowired
    private UserService userService;

    @Autowired
    public TeacherService teacherService;
    @PostMapping("/importData")
    @Transactional
    public R importData(@RequestParam("file") MultipartFile file,
                        @RequestParam("classId") Integer classId) {

        try {
            User user1 = ThreadLocalUtil.getUser();
            //获取文件的输入流
            InputStream inputStream = file.getInputStream();
            List<AddUserVo> list = EasyExcel.read(inputStream) //调用read方法
                    //注册自定义监听器，字段校验可以在监听器内实现
                    .registerReadListener(new StudentListener1())
                    .head(AddUserVo.class) //对应导入的实体类
                    .sheet(0) //导入数据的sheet页编号，0代表第一个sheet页，如果不填，则会导入所有sheet页的数据
                    .headRowNumber(1) //列表头行数，1代表列表头有1行，第2行开始为数据行
                    .doReadSync(); //开始读Excel，返回一个List<T>集合，继续后续入库操作
            System.out.println("文件"+list);
            Calendar calendar = Calendar.getInstance();
            int i = calendar.get(Calendar.YEAR);
            for (AddUserVo add : list) {
                User user = new User();
                user.setUserCard(add.getUserCard());
                user.setNickName(add.getUserName());
                user.setUserName(add.getUserPhone());
                String substring = add.getUserCard().substring(12, 18);
                user.setUserPass(substring);
                user.setUserEmail(add.getUserEmail());
                user.setUserPhone(add.getUserPhone());
                //学校ID 记得在token中得到
                user.setSchoolId(user1.getSchoolId());
                user.setUserSex(add.getUserSex().toString());
                user.setUserType("2");
                user.setUserStatus("0");
                Integer i1 = userService.AddUserXX(user);
                System.out.println(i1+"hahahahahahaha");
                if (i1!=1){
                    throw new RuntimeException("添加失败");
                }
                userService.addUserClass(user.getUserId().intValue(),classId);
                UserInfo userInfo=new UserInfo();
                userInfo.setUserId(user.getUserId().intValue());
                userInfo.setUserAddress(add.getUserAddress());
                userInfo.setUserPostscript(add.getUserPostscript());
                userInfo.setAddTime(LocalDateTime.now());
                userInfo.setStudentRecord(0);
                userInfo.setDirectionId(1);
//                userService.addUserInfo(userInfo);
            }

        } catch (Exception exception) {
            exception.printStackTrace();
            return R.error(StatusEnum.CUOWU_REPEAT);
        }

        return R.success(true);
    }

    @GetMapping("/getAllUserByClassId")
    public R getAllUserByClassId(@RequestParam("classId") Integer classId) {
        List<User> users = userService.selectUserByClassId(classId);
        return R.success(users);
    }
    @DeleteMapping("/deleteUser")
    public R deleteUser(@RequestParam("userId") Integer userId) {
        System.out.println("-____"+userId);
        Integer i = userService.deleteUser(userId);
        return R.success(i);
    }




    /**
     * 设置响应结果
     *
     * @param response    响应结果对象
     * @param rawFileName 文件名
     * @throws UnsupportedEncodingException 不支持编码异常
     */
    private void setExcelResponseProp(HttpServletResponse response, String rawFileName) throws UnsupportedEncodingException {

        //设置内容类型
        response.setContentType("application/vnd.vnd.ms-excel");
        //设置编码格式
        response.setCharacterEncoding("utf-8");
        //设置导出文件名称（避免乱码）
        String fileName = URLEncoder.encode(rawFileName.concat(".xlsx"), "UTF-8");
        // 设置响应头
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName);
    }
}
